﻿using System;
using System.Reflection;
using System.ComponentModel;

namespace System
{
    /// <summary>
    /// 扩展 Enum 类
    /// </summary>
    public static class EnumExtension
    {
        /// <summary>
        /// 显示中文的描述，自定义 Attribute 的类型应该为 ChineseDescriptionAttribute
        /// </summary>
        /// <param name="enumeration"></param>
        /// <returns></returns>
        public static string ToChineseDescription(this Enum enumeration)
        {
            var type = enumeration.GetType();
            var memberInfos = type.GetMember(enumeration.ToString()); // 得到枚举的字段，可能零个或一个或多个
            if (memberInfos.Length > 0)
            {
                var customEnumDesc = memberInfos[0].GetCustomAttributes(typeof(ChineseDescriptionAttribute), false); // 得到枚举的自定义 Attribute
                if (customEnumDesc.Length > 0)
                {
                    return ((ChineseDescriptionAttribute)customEnumDesc[0]).Text;
                }
            }
            return enumeration.ToString();
        }

        /// <summary>
        /// 显示枚举的描述，自定义 Attribute 的类型应该为 System.ComponentModel.DescriptionAttribute
        /// </summary>
        /// <param name="enumeration"></param>
        /// <returns></returns>
        public static string ToDescription(this Enum enumeration)
        {
            var type = enumeration.GetType();
            var memberInfos = type.GetMember(enumeration.ToString());
            if (memberInfos.Length > 0)
            {
                var attrs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }
            return enumeration.ToString();
        }
    }
}
